import asyncio
import logging

from openai import OpenAI


class OpenAIAPI:
    def __init__(self, api_key, base_url, model, max_concurrent_requests=10):
        self.client = OpenAI(api_key=api_key, base_url=base_url)
        self.model = model
        # 注意：在使用官方OpenAI库时，max_concurrent_requests参数可能不需要直接设置，因为库内部已经处理了并发控制。
        # 但是，如果你需要自定义并发限制，可以考虑使用asyncio.Semaphore或者类似机制。

    async def call_api(self, prompt: str) -> str:
        # 使用OpenAI库进行API调用
        return await self._call_openai_api(prompt)

    async def _call_openai_api(self, prompt: str) -> str:
        try:
            response = self.client.chat.completions.create(
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": prompt},
                ],
                model=self.model,
                stream=False,
                temperature=1.0,
            )
            return response.choices[0].message.content.strip()
        except Exception as e:
            logging.error(f"请求失败: {e}")
            return "API调用失败"

    async def batch_call_api(self, prompts: list[str]) -> list[str]:
        tasks = [self.call_api(prompt) for prompt in prompts]
        return await asyncio.gather(*tasks)